package cn.wolfcode.cms.util;


import cn.wolfcode.cms.domain.Employee;
import cn.wolfcode.cms.domain.SystemLog;
import cn.wolfcode.cms.service.IProductService;
import cn.wolfcode.cms.service.ISystemLogService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Setter;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

//系统日志切面
public class SystemLogAspect {
    @Setter
    private ISystemLogService systemLogService;
    public void write(JoinPoint jp) throws JsonProcessingException {

        //xml配置的日志切面是所有的service, 包括日志的service, 如果日志save操作也进行日志切面会出现死循环
        //所以需要额外排除
        if(jp.getTarget() instanceof  ISystemLogService){
            return;
        }
        if(jp.getTarget() instanceof IProductService){
            return;
        }
        //System.out.println("写日志了......");
        SystemLog log = new SystemLog();
        //日志时间
        log.setOpTime(new Date());
        //当前操作者
        log.setOpUser((Employee)SecurityUtils.getSubject().getPrincipal());

        //设置当前执行方法
        //System.out.println("当前方法所在类:" + jp.getTarget().getClass().getName());
        //System.out.println("当前方法名字:" + jp.getSignature().getName());
        //System.out.println("当前方法参数:" + jp.getArgs());
        log.setFunction(jp.getTarget().getClass().getName() + ":" + jp.getSignature().getName());
        //设置当前执行方法的参数
        log.setParams(new ObjectMapper().writeValueAsString(jp.getArgs()));

        //获取请求ip
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String ip = requestAttributes.getRequest().getRemoteAddr();
        log.setOpIp(ip);
        systemLogService.save(log);

    }
}
